package com.example.demo.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.Mapper.TaskMapper;
import com.example.demo.Pojo.Task;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/task")
public class TaskController {
    @Autowired
    TaskMapper taskMapper;

    @RequestMapping("/addTask")    //添加任务，参数：Task实体
    public int addTask(HttpServletRequest request){
        JSONObject task = JSONObject.parseObject(request.getParameter("task"));
        Task t = JSONObject.toJavaObject(task,Task.class);
        return taskMapper.insert(t);    //为1添加成功，0是失败
    }

    @RequestMapping("/allTask")    //查找所有任务,参数：userId
    public String allTask(HttpServletRequest request){
        QueryWrapper<Task> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",Long.parseLong(request.getParameter("userId")));
        List<Task> tasks = taskMapper.selectList(wrapper);
        return JSON.toJSONString(tasks);
    }

    @RequestMapping("/getTaskById")    //根据ID查找任务，参数：taskId
    public String getTaskById(HttpServletRequest request){
        Task task = taskMapper.selectById(request.getParameter("taskId"));
        return JSON.toJSONString(task);
    }
    
    @RequestMapping("/getTaskByDate")    //根据日期查找，参数：userId，天数n：0，1，7
    public String getHTaskByDate(HttpServletRequest request) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cd = Calendar.getInstance();
        cd.setTime(new Date());
        //增加天数
        cd.add(Calendar.DATE,Integer.parseInt(request.getParameter("n")));
        QueryWrapper<Task> wrapper = new QueryWrapper<>();
        wrapper.le("Date(taskGmtStart)",sdf.format(cd.getTime()))
                .ge("Date(taskGmtOver)",sdf.format(cd.getTime()));
        wrapper.eq("userId",Long.parseLong(request.getParameter("userId")));
        List<Task> tasks = taskMapper.selectList(wrapper);
        return JSON.toJSONString(tasks);
    }

    @RequestMapping("/getTaskByMonth")    //根据月份查找，参数：userId,  n，-1为上个月，1为下个月，以此类推
    public  String getTaskByMonth(HttpServletRequest request){
        Calendar cd = Calendar.getInstance();
        cd.setTime(new Date());
        //增加月数
        cd.add(Calendar.MONTH,Integer.parseInt(request.getParameter("n")));
        QueryWrapper<Task> wrapper = new QueryWrapper<>();
        wrapper.eq("month(taskGmtStart)",cd.get(Calendar.MONTH)+1);
        wrapper.eq("year(taskGmtStart)",cd.get(Calendar.YEAR));
        wrapper.eq("userId",Long.parseLong(request.getParameter("userId")));
        List<Task> tasks = taskMapper.selectList(wrapper);
        return JSON.toJSONString(tasks);
    }

    @RequestMapping("/getTaskByMonthOnCalendar")    //根据月份查找，参数：n，-1为上个月，1为下个月，以此类推
    public  String getTaskByMonthOnCalendar(HttpServletRequest request){ // 必须回传userId,可以指定月份，默认返回当前月的全部普通任务，使用Map数组，key指定了该任务所在日
        String userId = request.getParameter("userId");

        if (userId == null)
            return "-1"; // 未传入userId

        Calendar cd = Calendar.getInstance();
        cd.setTime(new Date());
        //增加月数
        cd.add(Calendar.MONTH,Integer.parseInt(request.getParameter("n")));
        QueryWrapper<Task> wrapper = new QueryWrapper<>();
        wrapper.eq("month(taskGmtStart)",cd.get(Calendar.MONTH)+1)
                .eq("userId",Long.parseLong(userId))
                .eq("year(taskGmtStart)",cd.get(Calendar.YEAR));
        List<Task> tasks = taskMapper.selectList(wrapper); // 设置需要显示的月份中的所有数据

        if(tasks.isEmpty())
            return "0"; // userId不正确，或无任务


        /*Map<Integer,Task> dayAndTasks = new HashMap<>();*/
        class DayAndTasks {
            private int day;
            private Task task;
            public void setDay(int day) {
                this.day = day;
            }

            public int getDay() {
                return day;
            }

            public void setTask(Task task) {
                this.task = task;
            }

            public Task getTask() {
                return task;
            }
        }
        DayAndTasks[] dayAndTasks = new DayAndTasks[tasks.size()];

        Calendar now = Calendar.getInstance();
        Calendar end   = Calendar.getInstance();

        for(int i = 0; i < tasks.size();i++){
            now.setTime(tasks.get(i).getTaskGmtStart());
            end.setTime(tasks.get(i).getTaskGmtOver()); // 记录当前循环的任务的开始结束时间，并使用now标记计算时间

            while(now.get(Calendar.DATE) <= end.get(Calendar.DATE)){ // 计算时间未超过end，则记录数据一次，数据起码会被记录一次以上
                dayAndTasks[i].setTask(tasks.get(i));
                dayAndTasks[i].setDay(now.get(Calendar.DATE)); // 存入日期和任务实体
                now.add(Calendar.DATE,1); // 计算时间加一天
            }
        }
        return JSON.toJSONString(dayAndTasks); // 返回Map数组
    }

    @RequestMapping("/toUpdateTask")    //前往update页面，参数taskId
    public String toUpdateTask(HttpServletRequest request){
        Task task = taskMapper.selectById(request.getParameter("taskId"));
        return JSON.toJSONString(task);
    }

    @RequestMapping("/updateTask")    //更新任务，task实体参数
    public int updateTask(HttpServletRequest request){
        JSONObject task = JSONObject.parseObject(request.getParameter("task"));
        Task t = JSONObject.toJavaObject(task,Task.class);
        return taskMapper.updateById(t);
    }

    @RequestMapping("/updateTaskByTasks")    //批量更新，参数：tasks
    public int updateTaskByTasks(HttpServletRequest request) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JavaType t  = objectMapper.getTypeFactory().constructParametricType(List.class, Task.class);

        List<Task> tasks = objectMapper.readValue(request.getParameter("tasks"),t);
        int s = 0;
        for (int i = 0; i < tasks.size(); i++) {
            s += taskMapper.updateById(tasks.get(i));
        }
        return s;
    }

    @RequestMapping("/deleteTask")    //逻辑删除任务，参数taskId
    public int delTask(HttpServletRequest request){
        return taskMapper.deleteById((request.getParameter("taskId")));
    }
}
